import '@/style/index.less'
import { createApp } from 'vue'
import App from './App.vue'
import setupRouterGuard from '@/router/guard'
import router from '@/router'
import { setupStore } from '@/store'
import { usePermissionStoreWithOut } from "@/store/modules/permission";
import { setupI18n } from '@/locales/setupI18n'
import { initAppConfigStore } from '@/settings/initAppConfig'
import { registerGlobComp } from '@/components/registerGlobComp'
import initAppUtils from '@/utils/app/index'
import { setupIcons } from '@/utils/icon'
import { createPermissionRouterGuardFromCache } from './router/guard/permissionGuard'
import Toast, { PluginOptions, POSITION } from "vue-toastification";
import "vue-toastification/dist/index.css";

declare module '@vue/runtime-core' {
  interface ComponentCustomProperties {
    $antIcons: any
    $getEnumDisplayName: any
    $formatToDate: any
  }
}

const toastOptions: PluginOptions = {  
  position: POSITION.TOP_RIGHT,
  timeout: false,
  closeOnClick: true,
  pauseOnFocusLoss: true,
  pauseOnHover: true,
  draggable: true,      
  closeButton: "button",
  icon: true,
  rtl: false,
  transition: 'Vue-Toastification__slideBlurred',
  newestOnTop: true,
}

async function bootstrap() {
  const app = createApp(App)

  app.use(Toast, toastOptions)

  setupIcons(app)

  setupStore(app)

  initAppConfigStore()

  registerGlobComp(app)

  await setupI18n(app)

  await initAppUtils(app)
  
  setupRouterGuard(router)

  app.directive('perms', {
    mounted(el, binding) {
      let permissionStore = usePermissionStoreWithOut()

      let isReject = false;
      let isAdmin = false;
      
      try {
        permissionStore.getPermissions.functions.forEach((e: {
          belongModule: any, rejectFunctions: any ,functions: any[] 
        }) => {          
          let module = e.belongModule.split(':')[0];
          if (module == '#') {
            isAdmin = true;
          }

          e.rejectFunctions.forEach((ie: string) => {
            let real = ie.split(':')[0]

            if (`${module}:${real}` == binding.value) {
              isReject = true;
              throw new Error('reject');
            }
          });
                   
          e.functions.forEach(ie => {
            let real = ie.split(':')[0]
            
            if (`${module}:${real}` == binding.value) {
              throw new Error('break');
            }
          });
        });
      } catch (error: any) {     
        if (error.message != 'reject') {
          return;
        }                
      }

      if (!isReject && isAdmin) {
        return;
      }

      el.parentNode && el.parentNode.removeChild(el)
      el.remove()
    }
  })
      
  app.use(router).mount('#app')

  createPermissionRouterGuardFromCache(router)
  
  console.log('页面挂载完毕');
}

bootstrap()